package logic

import (
	"bytes"
	"core/component/logger"
	"core/network"
	"io"
	"net"
	"net/http"
	"net/http/pprof"
	_ "net/http/pprof"
	"runtime/debug"
)

// HTTPHandler http handler
type HTTPHandler struct {
	Router *network.HttpRouter
}

func newHttpHandler() *HTTPHandler {
	httpHandler := &HTTPHandler{Router: network.NewHttpRouter()}
	return httpHandler
}

func startHTTPServer(httpAddr string, handler *HTTPHandler) {
	handler.Register()
	handler.RegisterProfiler()
	srv := network.HttpServer(handler)
	l, err := net.Listen("tcp", httpAddr)
	if err != nil {
		logger.Errorf("Listen http addr fail %d", httpAddr)
	}
	go func() {
		defer func() {
			if err := recover(); err != nil {
				logger.Error("[异常] http服务器出错", err, "\n", string(debug.Stack()))
			}
		}()
		if err = srv.Serve(l); err != nil {
			logger.Error("encountered an error while serving listener: ", err)
			panic(err)
		}
	}()
	logger.Infof("HttpServer Listening on %s", l.Addr().String())
}

func (hs *HTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// 把request的内容读取出来
	var bodyBytes []byte
	if r.Body != nil {
		bodyBytes, _ = io.ReadAll(r.Body)
	}
	// 把刚刚读出来的再写进去
	r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
	defer r.Body.Close()
	hs.Router.ServeHTTP(w, r)
}

func (hs *HTTPHandler) Register() {
}

// RegisterProfiler (注册性能监控方法)
func (hs *HTTPHandler) RegisterProfiler() {
	hs.Router.HandleFunc("GET", "/debug/pprof/", pprof.Index)
	hs.Router.HandleFunc("GET", "/debug/pprof/cmdline", pprof.Cmdline)
	hs.Router.HandleFunc("GET", "/debug/pprof/profile", pprof.Profile)
	hs.Router.HandleFunc("GET", "/debug/pprof/symbol", pprof.Symbol)
	hs.Router.HandleFunc("GET", "/debug/pprof/trace", pprof.Trace)
	//hs.Router.HandleFunc("POST", "/src_bin_version", srcBinVersionHandler)

	// 研发期间使用，稳定运营阶段，优先考虑屏蔽
	// Manually add support for paths linked to by index page at /debug/pprof/
	hs.Router.Handle("GET", "/debug/pprof/goroutine", pprof.Handler("goroutine"))
	hs.Router.Handle("GET", "/debug/pprof/heap", pprof.Handler("heap"))
	hs.Router.Handle("GET", "/debug/pprof/threadcreate", pprof.Handler("threadcreate"))
	hs.Router.Handle("GET", "/debug/pprof/block", pprof.Handler("block"))
	hs.Router.Handle("GET", "/debug/pprof/allocs", pprof.Handler("allocs"))

	//hs.Router.HandleFunc("GET", "/debug/set_log_level", setLogLevel) // 动态设置服日志级别
}
